# -*- coding: utf-8 -*-


'''eof
name:成长能力正向异动指标数量占比
code:Industry_Score_13
tableName:
columnName:
groups:行业评分模块
dependencies:INDUSTRY_INFO
type:常用指标
datasourceType:在线指标
description:
eof'''
from __future__ import division
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse
import datetime
import pandas as pd


null_type_list = ['', None, 'None', 'null', 'Null', 'NULL', '/', ' ',[]]
aList = [u'总资产增长率',u'营业收入增长率',u'毛利润增长率',u'所有者权益增长率',u'净利润增长率',u'经营活动产生的现金流量净额',u'投资活动产生的现金流量净额',u'筹资活动产生的现金流量净额',u'现金及现金等价物净增加额']
bList = [u'总负债增长率',u'负债权益比']
factor2 = 11

def timelist():
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        #计算factor1
        financeIndicatorDetail = data.get("financeIndicatorDetail")
        if financeIndicatorDetail in null_type_list:
            return u"缺失值"
        else:
            timeDict = {}
            errorTimes = 0
            for i in financeIndicatorDetail:
                try:
                    year = i.get('fiscalYear')
                    quarter = i.get('quarter')
                    if quarter == "Q2":
                        yearMonth = year + "07" 
                        timeDict.update({yearMonth:year+quarter})
                    elif quarter == "Q4":
                        yearMonth = str(int(year) + 1) + "01"
                        timeDict.update({yearMonth:year+quarter})
                    else:
                        errorTimes += 1
                except:
                    errorTimes += 1
            if errorTimes == len(financeIndicatorDetail):
                return u"缺失值"
            timeMax = timeDict[max(list(timeDict.keys()))]
            timeMaxChange = max(list(timeDict.keys()))
            timeRange = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset\
                                (months=i)).strftime('%Y%m%d')[:6] for i in range(0,11)]
            if timeMaxChange not in timeRange:
                return u"缺失值"
            if "Q2" in timeMax:
                timeSec = str(int(timeMax[0:4])-int(1)) + "Q4"
            else:
                timeSec = timeMax[0:4] + "Q2"
            return [timeMax,timeSec]
 
        
def Industry_Score_13():
    timeList = timelist()
    if timeList == u"缺失值":
        return u"缺失值"
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        financeIndicatorDetail = data.get("financeIndicatorDetail")
        if financeIndicatorDetail in null_type_list:
            return u"缺失值"
        else:
            DATA = pd.DataFrame(financeIndicatorDetail)
            DATA["TIME"] = DATA["fiscalYear"] +  DATA["quarter"]
            DATA = DATA[DATA["finItem"].isin(aList + bList)]
            if len(DATA) == 0:
                return u"缺失值"
            DATA1 = DATA[DATA["TIME"]== timeList[0]]
            DATA2 = DATA[DATA["TIME"]== timeList[1]]
            if len(DATA1) == 0 or len(DATA2) == 0:
                return u"缺失值"
            intersection = list(set(list(DATA1["finItem"])).intersection(set(list(DATA1["finItem"]))))
            if intersection == []:
                return u"缺失值"
            DATA3 = DATA1[pd.Series(DATA1["finItem"].isin(intersection),index = DATA1.index)].reset_index(drop=True)
            DATA4 = DATA2[pd.Series(DATA2["finItem"].isin(intersection),index = DATA2.index)].reset_index(drop=True)
            factor1 = 0
            errorTimes = 0
            for i in intersection:
                try:
                    dangqi = float(DATA3[DATA3["finItem"] == i]["meanValue"].reset_index(drop=True)[0])
                    shangqi = float(DATA4[DATA4["finItem"] == i]["meanValue"].reset_index(drop=True)[0])
                    indexType = DATA3[DATA3["finItem"] == i]["valueType"].reset_index(drop=True)[0]
                    indexType = DATA3[DATA3["finItem"] == i]["valueType"].reset_index(drop=True)[0]
                    if indexType not in ["1","2","3",1,2,3]:
                       errorTimes += 1
                       continue
                    if i in aList:
                        if indexType in ["1",1]:
                            if dangqi - shangqi > 10:
                                factor1 += 1
                        elif indexType in ["2",2,"3",3]:
                            if (dangqi - shangqi)/shangqi > 0.1:
                                factor1 += 1
                    if i in bList:
                        if indexType in ["1",1]:
                            if dangqi - shangqi < -10:
                                factor1 += 1
                        elif indexType in ["2",2,"3",3]:
                            if (dangqi - shangqi)/shangqi < -0.1:
                                factor1 += 1
                except:
                    errorTimes += 1
            if errorTimes == len(intersection):
                return u"缺失值"
            return round(factor1 / factor2,4)
        
result = Industry_Score_13()
                
